<template>
  <ContentDetailWrap :title="t('inventory.detail')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :disabled="!disabled" @click="handlePublish('all')">
        {{ t('market.SMCopywritingTasksDetail.fullRelease') }}
      </BaseButton>
    </template>
    <!--    回显-->
    <Descriptions class="m-b-50px" :schema="detailSchema" :data="descriptionsRow" />
    <!--    列表-->
    <el-table
      :data="tableData"
      border
      class="m-t-10px"
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center', background: '#f8f8f9', color: '#333333' }"
    >
      <el-table-column :label="t('expandCustomer.serialNumber')" prop="id" min-width="70" />
      <el-table-column
        :label="t('market.SMCopywritingTasksDetail.account')"
        prop="social_media_account_id"
        min-width="250"
      />
      <el-table-column
        :label="t('market.SMCopywritingTasksDetail.promptWords')"
        prop="cue_word"
        min-width="300"
      />
      <el-table-column
        :label="t('market.SMCopywritingTasksDetail.content')"
        prop="content"
        min-width="300"
      />
      <el-table-column
        :label="t('market.SMCopywritingTasksDetail.taskStatus')"
        :show-overflow-tooltip="true"
        min-width="150"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(taskStatusList, row.task_status) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('market.SMCopywritingTasksDetail.executionTime')"
        min-width="200"
        prop="execution_time"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('market.SMCopywritingTasksDetail.executionResult')"
        prop="execution_result"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('market.SMCopywritingTasksDetail.numberOfExecutions')"
        prop="redo_num"
        min-width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('market.SMCopywritingTasksDetail.publishingStatus')"
        :show-overflow-tooltip="true"
        min-width="150"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(publishStatusList, row.publish_status) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('market.SMCopywritingTasksDetail.publishTheResults')"
        prop="publish_results"
        min-width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="publish_url"
        min-width="100"
        :label="t('market.SMCopywritingTasksDetail.postALink')"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          <ElLink v-if="row.publish_url" type="primary" :href="row.publish_url" target="_blank"
            >查看
          </ElLink>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('market.SMCopywritingTasksDetail.createdBy')"
        prop="creator"
        min-width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('market.SMCopywritingTasksDetail.creationTime')"
        prop="create_time"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column fixed="right" label="操作" width="250">
        <template #default="{ row }">
          <el-button
            type="primary"
            v-if="row.task_status === 1 && (row.publish_status === 1 || row.publish_status === 4)"
            @click="handleChangeContent(row)"
            size="small"
          >
            {{ t('market.SMCopywritingTasksDetail.modifications') }}
          </el-button>
          <el-button
            type="primary"
            v-if="row.task_status === 1 && (row.publish_status === 1 || row.publish_status === 4)"
            @click="handlePublish('single', row)"
            size="small"
          >
            {{ t('market.SMCopywritingTasksDetail.publish') }}
          </el-button>
          <el-button
            v-if="row.task_status === 1 && (row.publish_status === 1 || row.publish_status === 4)"
            @click="handleGeneration(row)"
            size="small"
          >
            {{ t('market.SMCopywritingTasksDetail.rebuild') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    修改内容弹框-->
    <DialogChangeContent ref="DialogChangeContentRef" @refresh="getDetail" />
  </ContentDetailWrap>
</template>
<script setup lang="tsx">
import DialogChangeContent from './components/DialogChangeContent/index.vue'
import { Descriptions, type DescriptionsSchema } from '@/components/Descriptions'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { useEnumeratePicker } from '@/utils'
import { getPlatformSelectApi, getSMCDetailApi, publishSMCApi, rebuildApi } from '@/api/market'
import { ElButton, ElImage, ElMessage, ElMessageBox } from 'element-plus'

const { t } = useI18n()
const { push, go } = useRouter()
const { query } = useRoute()

const channelList = ref<Array<Record<string, any>>>([])
const languageList = ref<Array<Record<string, any>>>([])
const groupList = ref<Array<Record<string, any>>>([])
const taskStatusList = ref<Array<Record<string, any>>>([])
const publishStatusList = ref<Array<Record<string, any>>>([])

const tableLoading = ref(false)
const tableData = ref<Array<Record<string, any>>>([])
const DialogChangeContentRef = ref()

const disabled = computed(
  () =>
    tableData.value.flatMap((item: Record<string, any>) =>
      item.publish_status === 1 ? [item.id] : []
    ).length > 0
)

const descriptionsRow = ref<Record<string, any>>({})
const detailSchema = ref<DescriptionsSchema[]>([
  {
    field: 'channel_id',
    label: t('market.markSocialMediaAccount.channel'),
    slots: {
      default: (data: Record<string, any>) => {
        return <span>{useEnumeratePicker(channelList.value, data.channel_id)}</span>
      }
    }
  },
  {
    field: 'language',
    label: t('market.markSocialMediaAccount.language'),
    slots: {
      default: (data: Record<string, any>) => {
        return <span>{useEnumeratePicker(languageList.value, data.language_id)}</span>
      }
    }
  },
  {
    field: 'account_group_id',
    label: t('market.markSocialMediaAccount.group'),
    slots: {
      default: (data: Record<string, any>) => (
        <span>{useEnumeratePicker(groupList.value, data.account_group_id)}</span>
      )
    }
  },
  {
    field: 'mining_machine',
    label: t('market.industryNews.associatedMiners'),
    slots: {
      default: (data: Record<string, any>) => (
        <span>
          {data.mining_machine
            ? `${JSON.parse(data.mining_machine).brand} ${JSON.parse(data.mining_machine).name}`
            : ''}
        </span>
      )
    }
  },
  {
    field: 'crypto_news_title',
    label: t('market.industryNews.newsHeadlines')
  },
  {
    field: 'cue_word',
    label: t('market.industryNews.promptWords')
  },
  {
    field: 'imgs',
    label: t('market.industryNews.img'),
    slots: {
      default: (data: Record<string, any>) => (
        <>
          {data.imgs && data.imgs.length ? (
            <ElImage
              class="w-90px h-90px cursor-pointer"
              src={data.imgs[0].url}
              zoomRate={1.2}
              maxScale={7}
              previewTeleported={true}
              minScale={0.2}
              previewSrcList={dealPreviewMap(data.imgs)}
              fit="cover"
            />
          ) : (
            ''
          )}
        </>
      )
    }
  }
])

const dealPreviewMap = (val: any[]) => {
  if (!val || !val.length) return []
  return val.map((item) => item.url)
}

//修改内容
const handleChangeContent = (row: Record<string, any>) => {
  nextTick(() => {
    DialogChangeContentRef.value.dialogVisible = true
    DialogChangeContentRef.value.getBackShow(row)
  })
}
//发布
const handlePublish = (type: string, row?: Record<string, any>) => {
  if (
    type !== 'single' &&
    !tableData.value.flatMap((item: Record<string, any>) =>
      item.publish_status === 1 && item.task_status === 1 ? [item.id] : []
    ).length
  )
    return ElMessage.warning('正在生成文案内容，请等待文案生成之后再操作。')

  ElMessageBox.confirm(
    `是否确认${type === 'single' ? '发布' : '全量发布'}？`,
    t('purchase.logistics.tips'),
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      const resp = await publishSMCApi({
        ids:
          type === 'single'
            ? [row?.id]
            : tableData.value.flatMap((item: Record<string, any>) =>
                item.publish_status === 1 && item.task_status === 1 ? [item.id] : []
              )
      })
      if (resp.code === 0) {
        ElMessage.success(t('market.SMCopywritingTasksDetail.publishSuccessful'))
        await getDetail()
      }
    })
    .catch(() => {})
}

//重新生成
const handleGeneration = async (row: Record<string, any>) => {
  const resp = await rebuildApi(row.id)
  if (resp.code === 0) {
    ElMessage.success(t('market.SMCopywritingTasksDetail.operationSuccessful'))
    await getDetail()
  }
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getPlatformSelectApi({ field: 'all' })
  channelList.value = resp.data.channel
  languageList.value = resp.data.language
  groupList.value = resp.data.account_group
  taskStatusList.value = resp.data.task_status
  publishStatusList.value = resp.data.publish_status
}

const getDetail = async () => {
  const resp = (await getSMCDetailApi(query.id as string)) as any
  descriptionsRow.value = resp.data
  tableData.value = resp.data.sm_copywriting
}

onMounted(() => {
  getDropDownBoxInfo()
  getDetail()
})
</script>
<style lang="less" scoped></style>
